'use strict'
exports.main = async (event, context) => {
  const { code } = event
  const res = await uniCloud.httpclient.request(
    'https://api.weixin.qq.com/sns/jscode2session?appid=wx6f333004ac6dc895&secret=d1ec6297838cdb55fb9f9ae3088d8c9a&js_code=' +
      code +
      '&grant_type=authorization_code',
    {
      dataType: 'json',
    }
  )
  console.log(res.data, 'res')
  const openId = res.data.openid
  // 在此处连接数据库
  const db = uniCloud.database()
  const usersCollection = db.collection('users')

  // 查询 users 表，判断用户是否注册过
  const { data } = await usersCollection
    .where({
      openId: openId,
    })
    .get()
  console.log('🚀 ~ file: index.js:19 ~ exports.main= ~ queryResult:', data)
  //返回openId
  return {
    code: 0,
    openId: openId,
    userInfo: data[0] || [],
  }
}
